<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    public function index()
    {
        return view('admin.login.index');
    }
    public function in(Request $request)
    {
        if(!$request->ajax()) {
            json(2,'请求类型错误');
            return;
        }
        if(!($username = $request->input('username'))){
            json(2,'用户名不能为空');
            return;
        }
        if(!($password = $request->input('password'))){
            json(2,'密码不能为空');
            return;
        }
        if(!($data = DB::table('users')->where('username', $username)->first())){
            json(2,'用户名不存在');
            return;
        }
        if(md5(md5($password.$data->hash)) != $data->password){
            json(2,'密码错误');
            return;
        }
        $data = json_decode(json_encode($data), true);
        unset($data['password']);
        session(["info" => $data]);
        // 设置cookie自动登录
        if($remember = $request->input('remember')){
            // 存用户ID/md5 password+hash
            $info = array('id'=>$data['id'],'remember'=>$remember,'password'=>md5($password.$data['hash']));
            Cookie::queue('info', json_encode($info), $remember*1400);
        } else {
            Cookie::unqueue('info');
        }
        json(1,'登录成功');
        return;
    }
    public function out()
    {
        session()->flush();
        cookie()->unqueue('info');
        return redirect('/admin/login/index');
    }
}
